package com.roc.web.action.settlemgr;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblTransJnlsSettle;
import com.roc.service.IExcelService;
import com.roc.service.IPagenitionService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Component
@Scope("prototype")
@Namespace("/settlementmsg")
public class SettlementMsgAction extends PaginationBaseAction{

	private static final long serialVersionUID = 1L;

	private static Logger logger = LogManager.getLogger(SettlementMsgAction.class);
	
	private SettlementMsgSearchCondition searchCondition;
	
	@Autowired
	private IExcelService excelService;
	
	@Autowired
	private IPagenitionService pagenitionService;
	
	private InputStream excelFile;
	
	@Action(value="querySettleMsgJsp",results={@Result(name="success",location="/pages/settlementmsg/settlementMsgList.jsp"),@Result(name = "error", location = "/error.jsp")})
	public String queryMsginfoJsp(){
		try {
			Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
				addActionError("当前登录账号无权限访问!!!");
				return ERROR;
			}
		} catch (Exception e) {
			logger.error("结算信息页面跳转失败");
		}
		
		return SUCCESS;
	}
	
	@Action(value="querySettleMsgList",results={@Result(name="success",location="/pages/settlementmsg/settlementMsgList.jsp"),@Result(name = "error", location = "/error.jsp")})
	public String querySettlementMsgList(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		try {
			if(searchCondition == null){
				searchCondition = (SettlementMsgSearchCondition) getSearchConditionFromSession();
				if(searchCondition == null){
					searchCondition = new SettlementMsgSearchCondition();
				}
			}
			
			if("".equals(Constance.Null2EmptyTrim(searchCondition.getMinDate())) || "".equals(Constance.Null2EmptyTrim(searchCondition.getMaxDate()))){
				logger.info("结算查询查询条件日期为空");
				return SUCCESS;
			}
			
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			
			List<TblTransJnlsSettle> settleList = new ArrayList<TblTransJnlsSettle>();
			dealTheSearchRsList(searchRsList,settleList);
			
			//统计交易总金额，交易总笔数
			List<Object> countList = new ArrayList<Object>();
			if(rows>0){
				countList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			
			BigDecimal settleAmtTotal = new BigDecimal("0");
			BigDecimal totalNumTotal = new BigDecimal("0");
			
			if(countList != null && countList.size()>0){
				Iterator<Object> it = countList.iterator();
				while(it.hasNext()){
					Object[] obj = (Object[]) it.next();
					
					String totalNum = Constance.Null2EmptyTrim(obj[5]); 
					if(!"".equals(totalNum)){
						totalNumTotal = totalNumTotal.add(new BigDecimal(String.valueOf(Integer.parseInt(totalNum))));//;
					}else{
						totalNumTotal = totalNumTotal.add(new BigDecimal(String.valueOf(0)));
					}
					
					String setAmt = Constance.Null2EmptyTrim(obj[8]);
					if(!"".equals(setAmt)){
						settleAmtTotal = settleAmtTotal.add(new BigDecimal(String.valueOf(Double.parseDouble(setAmt))));//;
					}else{
						settleAmtTotal = settleAmtTotal.add(new BigDecimal(String.valueOf(0)));;
					}
					
					
				}
			}
			
			
			
			
			getRequest().setAttribute("settleList", settleList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			getRequest().setAttribute("totalNumTotal", totalNumTotal.toPlainString());
			getRequest().setAttribute("settleAmtTotal", settleAmtTotal.toPlainString());
			setSearchToConditionSession(searchCondition);
			
			
		} catch (Exception e) {
			logger.error("清算管理结算信息查询异常：{}",e);
		}
		return SUCCESS;
	}
	
	@Action(value="exportSettleMsgList",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xls",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/settlementmsg/settlementMsgList.jsp") })
	public String exportSettleMsgList(){
		try {
			if(searchCondition == null){
				searchCondition = (SettlementMsgSearchCondition) getSearchConditionFromSession();
				if(searchCondition == null){
					searchCondition = new SettlementMsgSearchCondition();
				}
			}
			
			if("".equals(Constance.Null2EmptyTrim(searchCondition.getMinDate())) || "".equals(Constance.Null2EmptyTrim(searchCondition.getMaxDate()))){
				logger.info("结算信息导出条件日期为空");
				return SUCCESS;
			}
			
			
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			
			List<TblTransJnlsSettle> settleList = new ArrayList<TblTransJnlsSettle>();
			List<String> amtList = new ArrayList<String>();
			dealTheSearchRsListForExport(searchRsList,settleList,amtList);
			
			
			SXSSFWorkbook work=excelService.exportSettlementMsgFlow(settleList,searchCondition.getMinDate(),searchCondition.getMaxDate(),amtList);

			 ByteArrayOutputStream output = new ByteArrayOutputStream();  
			         work.write(output);  
			   
			        byte[] ba = output.toByteArray();  
			         excelFile = new ByteArrayInputStream(ba);  
			         output.flush();  
			         output.close();
			
			
		} catch (Exception e) {
			logger.error("清算管理结算信息导出异常：{}",e);
		}
		return SUCCESS;
	}
	
	private void dealTheSearchRsList(List<Object> searchRsList,
			List<TblTransJnlsSettle> settleList) throws Exception {
		
		try {
			if(searchRsList != null && searchRsList.size() > 0){
				Iterator<Object> it = searchRsList.iterator();
				while(it.hasNext()){
					Object[] obj = (Object[]) it.next();
					TblTransJnlsSettle s = new TblTransJnlsSettle();
					s.setInsIdCd(Constance.Null2EmptyTrim(obj[1]));
					s.setMchtCd(Constance.Null2EmptyTrim(obj[2]));
					s.setMchtName(Constance.Null2EmptyTrim(obj[3]));
					String transAmt = Constance.Null2EmptyTrim(obj[4]);
					if(!"".equals(transAmt)){
						s.setTransAmt(Double.parseDouble(transAmt));
					}else{
						s.setTransAmt(0.00);
					}
					String totalNum = Constance.Null2EmptyTrim(obj[5]); 
					if(!"".equals(totalNum)){
						s.setTotalNum(Integer.parseInt(totalNum));
					}else{
						s.setTotalNum(0);
					}
					
					String mchtFee = Constance.Null2EmptyTrim(obj[6]);
					if(!"".equals(mchtFee)){
						s.setMchtFee(Double.parseDouble(mchtFee));
					}else{
						s.setMchtFee(0.00);
					}
					
					String trueFee = Constance.Null2EmptyTrim(obj[7]);
					if(!"".equals(trueFee)){
						s.setChlTrueFee(Double.parseDouble(trueFee));
					}else{
						s.setChlTrueFee(0.00);
					}
					
					String setAmt = Constance.Null2EmptyTrim(obj[8]);
					if(!"".equals(setAmt)){
						s.setMchtSetAmt(Double.parseDouble(setAmt));
					}else{
						s.setMchtSetAmt(0.00);
					}
					
					s.setBankName(Constance.Null2EmptyTrim(obj[9]));
					s.setBankCode(Constance.Null2EmptyTrim(obj[10]));
					s.setAccount(Constance.Null2EmptyTrim(obj[11]));
					s.setAccountName(Constance.Null2EmptyTrim(obj[12]));
					s.setAccType(Constance.Null2EmptyTrim(obj[13]));
					s.setSettleDate(Constance.Null2EmptyTrim(obj[14]));
					s.setSettleFlag(Constance.Null2EmptyTrim(obj[15]));
					s.setSetDate(Constance.Null2EmptyTrim(obj[16]));
					s.setFreezeFlag(Constance.Null2EmptyTrim(obj[17]));
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmmss");
					s.setDtCreate(sdf.parse(Constance.Null2EmptyTrim(obj[18])));
					s.setDtUpdate(sdf.parse(Constance.Null2EmptyTrim(obj[19])));
					String remark = Constance.Null2EmptyTrim(obj[20]);
					if("0".equals(remark)){
						s.setTypeName("普通交易结算");
					}else if("1".equals(remark)){
						s.setTypeName("扫码结算");
					}else{
						s.setTypeName("未知");
					}
					s.setInsCompanyCd(Constance.Null2EmptyTrim(obj[25]));
					settleList.add(s);
				}
			}
		} catch (Exception e) {
			throw new Exception("解析数据封装到结算信息实体类异常");
		}
		
	}
	
	private void dealTheSearchRsListForExport(List<Object> searchRsList,
			List<TblTransJnlsSettle> settleList,List<String> amtList) throws Exception {
		BigDecimal transAmtTotal = new BigDecimal("0");
		BigDecimal settleAmtTotal = new BigDecimal("0");
		BigDecimal bizAmtTotal = new BigDecimal("0");
		try {
			if(searchRsList != null && searchRsList.size() > 0){
				Iterator<Object> it = searchRsList.iterator();
				while(it.hasNext()){
					Object[] obj = (Object[]) it.next();
					TblTransJnlsSettle s = new TblTransJnlsSettle();
					s.setInsIdCd(Constance.Null2EmptyTrim(obj[1]));
					s.setMchtCd(Constance.Null2EmptyTrim(obj[2]));
					s.setMchtName(Constance.Null2EmptyTrim(obj[3]));
					String transAmt = Constance.Null2EmptyTrim(obj[4]);
					if(!"".equals(transAmt)){
						s.setTransAmt(Double.parseDouble(transAmt));
					}else{
						s.setTransAmt(0.00);
					}
					String totalNum = Constance.Null2EmptyTrim(obj[5]); 
					if(!"".equals(totalNum)){
						s.setTotalNum(Integer.parseInt(totalNum));
					}else{
						s.setTotalNum(0);
					}
					
					String mchtFee = Constance.Null2EmptyTrim(obj[6]);
					if(!"".equals(mchtFee)){
						s.setMchtFee(Double.parseDouble(mchtFee));
					}else{
						s.setMchtFee(0.00);
					}
					
					String trueFee = Constance.Null2EmptyTrim(obj[7]);
					if(!"".equals(trueFee)){
						s.setChlTrueFee(Double.parseDouble(trueFee));
					}else{
						s.setChlTrueFee(0.00);
					}
					
					String setAmt = Constance.Null2EmptyTrim(obj[8]);
					if(!"".equals(setAmt)){
						s.setMchtSetAmt(Double.parseDouble(setAmt));
					}else{
						s.setMchtSetAmt(0.00);
					}
					
					s.setBankName(Constance.Null2EmptyTrim(obj[9]));
					s.setBankCode(Constance.Null2EmptyTrim(obj[10]));
					s.setAccount(Constance.Null2EmptyTrim(obj[11]));
					s.setAccountName(Constance.Null2EmptyTrim(obj[12]));
					s.setAccType(Constance.Null2EmptyTrim(obj[13]));
					s.setSettleDate(Constance.Null2EmptyTrim(obj[14]));
					s.setSettleFlag(Constance.Null2EmptyTrim(obj[15]));
					s.setSetDate(Constance.Null2EmptyTrim(obj[16]));
					s.setFreezeFlag(Constance.Null2EmptyTrim(obj[17]));
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmmss");
					s.setDtCreate(sdf.parse(Constance.Null2EmptyTrim(obj[18])));
					s.setDtUpdate(sdf.parse(Constance.Null2EmptyTrim(obj[19])));
					String remark = Constance.Null2EmptyTrim(obj[20]);
					if("0".equals(remark)){
						s.setTypeName("普通交易结算");
					}else if("1".equals(remark)){
						s.setTypeName("扫码结算");
					}else{
						s.setTypeName("未知");
					}
					s.setInsCompanyCd(Constance.Null2EmptyTrim(obj[25]));
					
					transAmtTotal = transAmtTotal.add(new BigDecimal(String.valueOf(s.getTransAmt())));
					settleAmtTotal = settleAmtTotal.add(new BigDecimal(String.valueOf(s.getMchtSetAmt())));
					bizAmtTotal = bizAmtTotal.add(new BigDecimal(String.valueOf(String.valueOf(s.getMchtFee()))));
					
					settleList.add(s);
				}
				
				amtList.add(transAmtTotal.toPlainString());
				amtList.add(settleAmtTotal.toPlainString());
				amtList.add(bizAmtTotal.toPlainString());
			}
			
		} catch (Exception e) {
			throw new Exception("解析数据封装到结算信息实体类异常");
		}
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_MSG_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (SettlementMsgSearchCondition)getSession().getAttribute(SEARCH_SESSION_MSG_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}

	public SettlementMsgSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(SettlementMsgSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	
	public String getExcelName() {
		String excelName="结算详情"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				//e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}

}
